# coding=utf-8
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import get_current_site
from django.core.mail import send_mail
from django.db import transaction
from django.http import HttpResponse, HttpResponseNotAllowed
from django.shortcuts import render, redirect
from django.template import loader
from django.views.decorators.cache import never_cache

from account.forms import RegisterForm, ProfileForm, AvatarForm
from account.models import User
from mysite.utils import generate_token_by_user
from team.models import Team, TeamMemberShip


@never_cache
@transaction.atomic
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                user = form.save()
                team = Team(name=form.cleaned_data['team'], owner=user)
                team.save()
                team_member_ship = TeamMemberShip(team=team, member=user, role='owner')
                team_member_ship.save()

            if user:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
                user.active_token = token = generate_token_by_user(user, 'account.register.active')
                c = {
                    'domain': domain,
                    'site_name': site_name,
                    'user': user,
                    'token': token,
                    'protocol': 'http'
                }
                user.save()
                subject = loader.render_to_string('account/account_active_subject.txt', c)
                # Email subject *must not* contain newlines
                subject = ''.join(subject.splitlines())
                email = loader.render_to_string('account/account_active_email.html', c)
                send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email])
            messages.success(request, '注册成功')
            return redirect('login')
    else:
        form = RegisterForm()

    context = {
        'title': '注册',
        'form': form,
    }
    return render(request, 'site/register.html', context)


@never_cache
def login(request):
    from django.contrib.auth.views import login

    context = {
        'title': '登录'
    }

    defaults = {
        'extra_context': context,
        'template_name': 'site/login.html',
    }
    return login(request, **defaults)


@never_cache
def logout(request):
    from django.contrib.auth import logout

    logout(request)
    return redirect('login')


@never_cache
def active(request, token):
    try:
        user = User.objects.get(active_token=token)
    except User.DoesNotExist:
        messages.error(request, '令牌不正确')
    else:
        user.is_active = True
        user.save()
    return request('login')


def password_reset(request):
    from django.contrib.auth.views import password_reset

    context = {
        'title': '重置密码',
    }
    defaults = {
        'extra_context': context,
        'template_name': 'site/password_reset.html',
        'from_email': settings.DEFAULT_FROM_EMAIL,
    }
    return password_reset(request, **defaults)


def password_reset_done(request):
    from django.contrib.auth.views import password_reset_done

    context = {
        'title': '密码重置链接已发送',
    }
    defaults = {
        'extra_context': context,
        'template_name': 'site/password_reset_done.html',
    }
    return password_reset_done(request, **defaults)


def password_reset_confirm(request, uidb64=None, token=None):
    from django.contrib.auth.views import password_reset_confirm

    context = {
        'title': '密码重置',
    }
    defaults = {
        'extra_context': context,
        'template_name': 'site/password_reset_confirm.html',
    }
    return password_reset_confirm(request, uidb64=uidb64, token=token, **defaults)


def password_reset_complete(request):
    from django.contrib.auth.views import password_reset_complete

    context = {
        'title': '密码重置完成',
    }
    defaults = {
        'extra_context': context,
        'template_name': 'site/password_reset_complete.html',
    }
    return password_reset_complete(request, **defaults)


@login_required
def profile(request):
    user = request.user
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人资料更新成功')
            return redirect('profile')
    else:
        form = ProfileForm(instance=user)

    context = {
        'title': '个人资料',
        'user': user,
        'form': form
    }
    return render(request, 'account/profile.html', context)


@never_cache
@login_required
def avatar(request):
    user = request.user
    if request.method == 'POST':
        import json

        form = AvatarForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            user.save()
            response = json.dumps({'success': True, 'avatar': user.avatar.url})
        else:
            response = json.dumps({'success': False, 'message': form.errors.get('avatar')})
        return HttpResponse(response, content_type='text/json')
    else:
        return HttpResponseNotAllowed(['POST'])



